package com.outsider.weixin.controller;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.demo.WeixinApiController;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.MessageApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.session.WxSession;
import com.jfinal.weixin.sdk.session.WxSessionManager;
import com.outsider.interceptor.ResponseHeaderInterceptor;
import com.outsider.util.weather.SimpleWeather;
import com.outsider.util.weather.WeatherApi;
import com.outsider.weixin.dao.Location;
import com.outsider.weixin.dao.User;

@Before(ResponseHeaderInterceptor.class)
public class MyApiController extends WeixinApiController {
/*    public void sendNoteMsg()
    {
         String str="Test";
         ApiResult apiResult=CustomServiceApi.sendText("ocvcps_0rRG_p6t-_vIUPSVXdhlI", str);
         renderText(apiResult.getJson());
         
    }*/
	public void getOpenID(){
		String code=getPara("code");
		if (code.equals("test")) {
			renderJson("openID","ocvcps_0rRG_p6t-_vIUPSVXdhlI");
			return;
		}
    	SnsAccessToken snsToken=SnsAccessTokenApi.getSnsAccessToken(PropKit.get("appId"), PropKit.get("appSecret"), code.split("&")[0]);
    	renderJson("openID",snsToken.getOpenid());
	}
	
	public void getWeatherData(){
		String openID=getPara("openID");
        WxSessionManager sessionManager = ApiConfigKit.getWxSessionManager();
        WxSession session = sessionManager.get(openID);
		User user=User.dao.findByOpenID(openID);
        Location location=Location.dao.findLocationByUserID(user.getID());
        
        SimpleWeather simpleWeather;
        if (session==null||null==session.getAttribute("weatherData")) 
        	simpleWeather=WeatherApi.getTodayWeather(location.getLongitude().toString(), location.getLatitude().toString());
        else
        	simpleWeather=(SimpleWeather) session.getAttribute("weatherData");
        renderJson(simpleWeather);
	}
}
